//
//  ETNavBarTransparent.swift
//  ETNavBarTransparentDemo
//
//  Created by Bing on 2017/3/1.
//  Copyright © 2017年 tanyunbing. All rights reserved.
//

import UIKit



extension DispatchQueue {
    
    private static var onceTracker = [String]()
    
    public class func once(token: String, block: () -> Void) {
        objc_sync_enter(self)
        defer { objc_sync_exit(self) }
        
        if onceTracker.contains(token) {
            return
        }
        
        onceTracker.append(token)
        block()
    }
}

extension UIColor
{
    fileprivate static var __tiny:UIColor{
        get{
            return EeTopStyle.default.navTintColor
        }
    }
}

typealias NavigationController = EeNavigationController
open class EeNavigationController:UINavigationController,UINavigationControllerDelegate{
    static var isSwizzle:Bool = true
}

extension EeNavigationController{
//    open override func viewDidLoad() {
//        self.navigationBar.buildMoBack()
//        super.viewDidLoad()
//        self.navigationBar.navigationController = self
//        self.navigationBar.centerBack.style = self.topViewController?.top_style ?? .default
//
//    }
//    @objc func et_updateInteractiveTransition(_ percentComplete: CGFloat) {
//        guard let topViewController = topViewController, let coordinator = topViewController.transitionCoordinator else {
//            et_updateInteractiveTransition(percentComplete)
//            return
//        }
//
//
//        let fromViewController = coordinator.viewController(forKey: .from)
//        let toViewController = coordinator.viewController(forKey: .to)
//
//        let fromStyle = fromViewController?.top_style ?? EeTopStyle.default
//        let toStyle = toViewController?.top_style ?? EeTopStyle.default
//
//
//        // Tint Color
//        let fromColor = fromStyle.navBarTintColor
//        let toColor = toStyle.navBarTintColor
//        let newColor = UIColor.averageColor(fromColor: fromColor, toColor: toColor, percent: percentComplete)
//        navigationBar.tintColor = newColor
//        self.navigationBar.updatePopScale(scale: percentComplete)
//
//
//        if EeNavigationController.isSwizzle
//        {
////            et_updateInteractiveTransition(percentComplete)
//        }
//    }
//
//    open override func viewWillAppear(_ animated: Bool) {
//        super.viewWillAppear(animated)
//        self.navigationBar.stop(at: topViewController!)
//        self.topViewController?.top_style.playUp()
//    }

    @objc open func et_popToViewController(_ viewController: UIViewController, animated: Bool) -> [UIViewController]? {
        //        self.navigationBar.leftBack.style = self.topViewController?.top_style?.navBarBgStyle ?? .default
        navigationBar.popTo(controller: viewController, animated: true)
        return et_popToViewController(viewController, animated: animated)
    }


    @objc open func et_popToRootViewController(animated: Bool) -> [UIViewController]? {


        if self.viewControllers.count > 1
        {
            self.navigationBar.popTo(controller: self.viewControllers.first!, animated: animated)
        }

        return et_popToRootViewController(animated: animated)
    }



}

extension EeNavigationController {
    
    override open var preferredStatusBarStyle: UIStatusBarStyle {
        return topViewController?.preferredStatusBarStyle ?? .default
//        return topViewController?.top_style.statusBarStyle ?? .default
    }
    
    open override func viewDidLoad() {
        navigationBar.shadowImage = UIImage.newImage(.clear)
        navigationBar.setBackgroundImage(UIImage.newImage(.clear), for: .default)
        super.viewDidLoad()
        self.delegate = EeTopNavigationDelegate()

        //        self.interactivePopGestureRecognizer?.addTarget(self, action: #selector(popGesture(edgePan:)))
    }
    
    @objc func popGesture(edgePan:UIScreenEdgePanGestureRecognizer) {
        
        
        let progress = edgePan.location(in:self.view).x / self.view.bounds.width
        if edgePan.state == UIGestureRecognizer.State.began {
        } else if edgePan.state == UIGestureRecognizer.State.changed {
            self.et_updateInteractiveTransition(progress)
            
        } else if edgePan.state == UIGestureRecognizer.State.cancelled || edgePan.state == UIGestureRecognizer.State.ended {
            //            if progress > 0.5 {
            //                self.et_updateInteractiveTransition(1)
            //            } else {
            //                self.et_updateInteractiveTransition(0)
            //            }
        }
    }
    open override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    
        self.navigationBar.stop(at: topViewController!)
        self.topViewController?.top_style.playUp()
    }
    open override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
//        self.navigationBar.stop(at: topViewController!)
//        self.topViewController?.top_style.playUp()
    }
    
    private static let onceToken = UUID().uuidString
    
    public class func open_nav_swizzle() {
        
        guard self == NavigationController.self else { return }
        DispatchQueue.once(token: onceToken) {
            let needSwizzleSelectorArr = [
                (Selector(("_updateInteractiveTransition:")),#selector(EeNavigationController.et_updateInteractiveTransition)),
                //                (#selector(NavigationController.pushViewController),#selector(NavigationController.et_popToViewController)),
                (#selector(EeNavigationController.popToViewController),#selector(EeNavigationController.et_popToViewController)),
                (#selector(EeNavigationController.popToRootViewController),#selector(EeNavigationController.et_popToRootViewController))
            ]
            
            for selector in needSwizzleSelectorArr {
                let originalMethod = class_getInstanceMethod(self, selector.0)
                let swizzledMethod = class_getInstanceMethod(self, selector.1)
                method_exchangeImplementations(originalMethod!, swizzledMethod!)
            }
            UIViewController.open_top_swizzle()
            
        }
    }
    
    @objc open func et_updateInteractiveTransition(_ percentComplete: CGFloat) {
        guard let topViewController = topViewController, let coordinator = topViewController.transitionCoordinator else {
            et_updateInteractiveTransition(percentComplete)
            return
        }
        
        
        let fromViewController = coordinator.viewController(forKey: .from)
        let toViewController = coordinator.viewController(forKey: .to)
        
        let fromStyle = fromViewController?.top_style ?? EeTopStyle.default
        let toStyle = toViewController?.top_style ?? EeTopStyle.default
        
        
        // Tint Color
        let fromColor = fromStyle.navTintColor
        let toColor = toStyle.navTintColor
        let newColor = UIColor.averageColor(fromColor: fromColor, toColor: toColor, percent: percentComplete)
        navigationBar.tintColor = newColor
        self.navigationBar.updatePopScale(scale: percentComplete)
        
        //swizzle 时需要打来注释
        if EeNavigationController.isSwizzle
        {
            et_updateInteractiveTransition(percentComplete)
        }
    }
    

    
//    @objc override open func et_popToViewController(_ viewController: UIViewController, animated: Bool) -> [UIViewController]? {
//        //        self.navigationBar.leftBack.style = self.topViewController?.top_style?.navBarBgStyle ?? .default
//       navigationBar.popTo(controller: viewController, animated: true)
//        return et_popToViewController(viewController, animated: animated)
//    }
//
//
//    @objc override open func et_popToRootViewController(animated: Bool) -> [UIViewController]? {
//
//
//        if self.viewControllers.count > 1
//        {
//            self.navigationBar.popTo(controller: self.viewControllers.first!, animated: animated)
//        }
//
//        return et_popToRootViewController(animated: animated)
//    }
    
    open override func pushViewController(_ viewController: UIViewController, animated: Bool) {

//        viewController.top_style.playUp()

        if self.topViewController != nil{
            self.navigationBar.pushTo(controller: viewController, animated: animated)
        }
        if self.viewControllers.count > 0
        {
//            viewController.hidesBottomBarWhenPushed = true
            
        }
        super.pushViewController(viewController, animated: animated)
        
    }
}





//extension UINavigationController: UINavigationBarDelegate {
//    public func navigationBar(_ navigationBar: UINavigationBar, shouldPop item: UINavigationItem) -> Bool {
//        weak var wself = self
//        navigationBar.titleTextAttributes = topViewController?.top_style.titleTextAttributes//侧滑返回拖动开始时遇先设置titleTextAttributes
//        if let topVC = topViewController, let coor = topVC.transitionCoordinator, coor.initiallyInteractive {
//            if #available(iOS 10.0, *) {
//                coor.notifyWhenInteractionChanges({ (context) in
//                    wself?.dealInteractionChanges(context)
//                })
//            } else {
//                coor.notifyWhenInteractionEnds({ (context) in
//                    wself?.dealInteractionChanges(context)
//                })
//            }
//            return true
//        }
//
//        let itemCount = navigationBar.items?.count ?? 0
//        let n = viewControllers.count >= itemCount ? 2 : 1
//        let popToVC = viewControllers[viewControllers.count - n]
//
//        if #available(iOS 13.0, *) {
//        }else{
//            popToViewController(popToVC, animated: true)
//
//        }
////        popToViewController(popToVC, animated: true)
//        navigationBar.tintColor = popToVC.top_style.navTintColor
//
//        return true
//    }
//
//    public func navigationBar(_ navigationBar: UINavigationBar, shouldPush item: UINavigationItem) -> Bool {
//        navigationBar.tintColor = topViewController?.top_style.navTintColor ?? EeTopStyle.default.navTintColor
//
//        navigationBar.titleTextAttributes = topViewController?.top_style.titleTextAttributes
//
////        navigationBar.pushTo(controller: topViewController!, animated: true)
//        return true
//    }
//
//    private func dealInteractionChanges(_ context: UIViewControllerTransitionCoordinatorContext) {
////        self.navigationBar.leftBack.style = self.topViewController?.top_style ?? .default
//
//        weak var wself = self
//        let animations: (UITransitionContextViewControllerKey) -> () = {
//            //该代码块下面的执行带有动画
//            if let top = self.topViewController,let to = context.viewController(forKey: $0)
//            {
//                if to === top{//is confirm pop
//
////                    wself?.navigationBar.popTo(controller:to, animated: false)
//                }
//                else{//canle pop
////                    print("------------canle pop==to\(to.title)==\(top.title)")
//                    wself?.navigationBar.pushTo(controller: to, animated: false)
////                    wself?.navigationBar.stop(at: context.viewController(forKey: $0)!)
//                }
//            }
//            context.viewController(forKey: $0)?.top_style.playUp()
//            wself?.navigationBar.tintColor = context.viewController(forKey: $0)?.top_style.navTintColor ?? EeTopStyle.default.navTintColor
//            wself?.navigationBar.titleTextAttributes = context.viewController(forKey: $0)?.top_style.titleTextAttributes
//        }
//
//        if context.isCancelled {
////            print("=================0000000")
////            if !EeNavigationController.isSwizzle{
////                    self.et_updateInteractiveTransition(0)
////            }
////            wself?.navigationBar.stop(at: self.topViewController!)
////            if let index = self.navigationController?.indexOf(controller: self.topViewController!)
////            {
////                if index > 1
////                {
////                    let ctrs = self.navigationController!.viewControllers
////                    let ctr = ctrs[index-1]
////                    self.navigationController?.navigationBar.popTo(controller:ctr, animated: false)
////
////                }
////            }
//            let cancelDuration: TimeInterval = context.transitionDuration * Double(context.percentComplete)
//            UIView.animate(withDuration: cancelDuration) {
//                animations(.from)
//            }
//        } else {
////            self.navigationBar.popTo(controller: self.topViewController!, animated: true)
////            if !EeNavigationController.isSwizzle{
////                                self.et_updateInteractiveTransition(1)
////            }
//
//            self.navigationBar.popTo(controller: self.topViewController, animated: false)
////            wself?.navigationBar.pushTo(controller: self.topViewController!, animated: false)
//            let finishDuration: TimeInterval = context.transitionDuration * Double(1 - context.percentComplete)
//            UIView.animate(withDuration: finishDuration) {
//                animations(.to)
//            }
//        }
//    }
//}



